import json
from django.core.management.base import BaseCommand
from paper.models import Category


class Command(BaseCommand):
    help = 'Insert categories from JSON file into the database'

    def handle(self, *args, **kwargs):
        with open('myapp/categories.json', 'r', encoding='utf-8') as file:
            categories_data = json.load(file)

        category_map = {}

        for category_data in categories_data:
            name = category_data['name']
            parent_name = category_data['parent']

            if parent_name:
                parent = category_map[parent_name]
            else:
                parent = None

            category, created = Category.objects.get_or_create(name=name, parent=parent)
            category_map[name] = category

            if created:
                self.stdout.write(self.style.SUCCESS(f'Successfully created category "{name}"'))
            else:
                self.stdout.write(self.style.WARNING(f'Category "{name}" already exists'))

        self.stdout.write(self.style.SUCCESS('All categories inserted successfully'))
